<?php

namespace App\Http\Controllers\Admin\Transport;

use App\Exceptions\AppException;
use App\Exports\TakeOrderExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\Transport\OrderRequest;
use App\Models\AgentModel;
use App\Models\airline\base\FlightModel as BaseFlightModel;
use App\Models\airline\base\RouteModel;
use App\Models\base\SubjectModel;
use App\Models\client\CommonPriceModel;
use App\Models\client\PriceDetailModel;
use App\Models\CountryModel;
use App\Models\customer\PriceModel;
use App\Models\CustomerModel;
use App\Models\DictionaryModel;
use App\Models\finance\PayableTakeOrderModel;
use App\Models\finance\ReceivableGenericDetailModel;
use App\Models\finance\ReceivableGenericModel;
use App\Models\finance\ReceivableTakeOrderDetailModel;
use App\Models\finance\ReceivableTakeOrderModel;
use App\Models\FlightItemModel;
use App\Models\OrderModel;
use App\Models\OrderNodeLogModel;
use App\Models\TakeOrderLogModel;
use App\Models\TakeOrderModel;
use App\Models\TakeOrderNodeLogModel;
use App\Models\TakeOrderRecModel;
use App\Models\TakeOrderSpecialModel;
use App\Models\TakeOrderWfModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class TakeOrder extends Controller
{
    use OrderRequest;

    /**
     * 构建查询条件
     */
    private function buildQuery(Request $request)
    {
        $sns = $request->input('sns', '');
        $customer_type_id = $request->input('customer_type', '');
        $customer_name = $request->input('customer_name', '');
        $flight_number = $request->input('flight_number', '');
        $status = $request->input('status', '');
        $des_country_id = $request->input('des_country_id', 0);
        $customer_visible = $request->input('customer_visible', '');
        $settle_again = $request->input('settle_again', '');
        $startTime = $request->input('startTime', '');
        $endTime = $request->input('endTime', '');
        $fill_admin_id = intval($request->input('fill_admin_id', 0));

        $query = TakeOrderModel::query()->whereHas('orders')
            ->with(['orders', 'fill_admin', 'customer', 'flight'])
            ->withCount('orders');

        if($customer_name){
            $query->whereHas('customer', function($query) use($customer_name) {
                $query->where('name', 'like', "%{$customer_name}%");
            });
        }

        if($customer_type_id){
            $query->whereHas('customer', function($query) use($customer_type_id) {
                $query->where('customer_type_id', $customer_type_id);
            });
        }

        if($startTime && $endTime){
            $query->whereHas('flight', function($query) use($startTime,$endTime) {
                if($startTime && $endTime){
                    $query->whereBetween('take_off_time', [$startTime, $endTime]);
                }
            });
        }

        if($des_country_id) {
            $query->whereHas('flight', function($query) use($des_country_id) {
                $query->where('arrive_port_code', $des_country_id);
            });
        }

        if($flight_number) {
            $query->whereIn('flight_id', function($query) use ($flight_number){
                $query->select('flight_id')
                    ->from((new FlightItemModel())->getTable())
                    ->whereIn('airline_flight_id', function($query) use ($flight_number){
                        $query->select('id')
                            ->from((new BaseFlightModel())->getTable())
                            ->where('flight_number', $flight_number);
                    });
            });
        }

        if(is_numeric($settle_again) && $settle_again == 0) {
            $query->where('reality_weight', 0);
        }

        if(is_numeric($settle_again) && $settle_again == 1) {
            $query->where('reality_weight', '<>',  0);
        }

        if($sns) {
            $sn_arr = explode(',', $sns);
            $query->whereIn('sn', $sn_arr);
        }

        if($status) {
            $query->where('status', $status);
        }

        if($customer_visible != ''){
            $query->where('show_sn', $customer_visible + 1);
        }

        if($fill_admin_id) {
            $query->where('fill_admin_id', $fill_admin_id);
        }

        return $query;
    }

    /**
     * 格式化数据为统一格式
     */
    private function formatListData($items)
    {
        return $items->map(function($item) {
            //航线
            $route_ids = $item->flight?->items?->pluck('route_id') ?? [];
            $routes = RouteModel::whereIn('id', $route_ids)->pluck('code')->toArray();

            //航班号
            $airline_flight_ids = $item->flight?->items?->pluck('airline_flight_id') ?? [];
            $flight_no = BaseFlightModel::whereIn('id', $airline_flight_ids)->pluck('flight_number')->toArray();

            //目的地
            $arrive_port_code = $item->destination ?? '';
            //始发地
            $start_port_code = $item->flight->start_port_code ?? '';
            
            //入库体积
            $storage_volume = $item->orders->sum('storage_volume');

            //分单数
            $split_order_count = 0;
            foreach($item->orders as $order) {
                $split_order_count += $order->split_order_addr?->count() ?? 0;
            } 

            return [
                'id' => $item->id,
                'customer_name' => $item->customer->name ?? '',
                'customer_sn' => $item->customer->sn ?? '',
                'customer_type' => $item->customer?->customer_type->name ?? '',
                'sn' => $item->sn,
                'status_name' => TakeOrderModel::STATUS_MAPS[$item->status] ?? '',
                'show_sn' => TakeOrderModel::SHOW_MAPS[$item->show_sn] ?? '',
                'route' => implode(',', $routes),
                'take_off_time' => $item->flight->take_off_time ?? '',
                'flight_no' => implode(',', $flight_no),
                'order_count' => $item->orders_count,
                'slipt_order_count' => $split_order_count,
                'big_pkgs' => $item->orders->sum('big_pkgs'),
                'arrive_port_code' => $arrive_port_code,
                'start_port_code' => $start_port_code,
                'storage_volume' => round($item->volume_weight / 167, 4),
                'volume_weight' => $item->volume_weight,
                'storage_weight' => round($item->orders->sum('storage_weight'), 4),
                'reality_weight' => $item->reality_weight,
                'settle_volume_weight' => $item->volume_weight,
                'rec_p' => $item->rec_p,
                'rec_p_text' => TakeOrderModel::$rec_p[intval($item->rec_p)] ?? '',
                'fee_weight' => $item->fee_weight,
                'fill_staff' => $item->fill_admin?->staff->name ?? '',
                'set_weight_staff' => $item->set_weight_admin?->staff->name ?? '',
                'created_at' => $item->created_at->toDateTimeString(),
                'flight_info' => $item->flight_info ?? '',
                'flight_info_show' => $item->flight_info_show,
                'grass_files' => $item->grass_files ? json_decode($item->grass_files,  true) : [],
                'final_files' => $item->final_files ? json_decode($item->final_files,  true) : [],
                'aircompany_files' => $item->aircompany_files ? json_decode($item->aircompany_files,  true) : [],
                'orders' => $item->orders->map(function($order) {
                    return [
                        'id' => $order->id,
                        'sn' => $order->sn,
                        'storage_weight' => $order->storage_weight,

                        //香港装车杂费
                        'hk_take_weight' => $order->hk_take_weight,
                        'hk_take_fee' => $order->hk_take_fee,
                        'hk_take_sign_fee' => $order->hk_take_sign_fee,
                        'hk_take_park_fee' => $order->hk_take_park_fee,
                        'hk_take_remark' => $order->hk_take_remark,

                        //香港自送杂费
                        'hk_zs_weight' => $order->hk_zs_weight,
                        'hk_zs_sign_fee' => $order->hk_zs_sign_fee,
                        'hk_zs_park_fee' => $order->hk_zs_park_fee,
                        'hk_zs_remark' => $order->hk_zs_remark,

                        //单证报关
                        'separate_dec_weight' => $order->separate_dec_weight,
                        'separate_dec_volume' => $order->separate_dec_volume,
                        'separate_dec_page_fee' => $order->separate_dec_page_fee,
                        'separate_dec_method' => $order->separate_dec_method,
                        'separate_dec_other' => $order->separate_dec_other,
                    ];
                }),
                'wf' => $item->wf,
            ];
        });
    }

    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);

        $query = $this->buildQuery($request);
        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $this->formatListData($items);

        return $this->success(['list' => $list, 'total' => $total]);
    }

    //起飞
    public function takeoff(Request $request) {
        $ids = $request->input('ids', []);
        $time = $request->input('time', null);
//        if(!$time) {
//            return $this->error('请选择起飞时间');
//        }

        if(!is_array($ids) || empty($ids)) {
            return $this->error('请选择提单');
        }

        $take_orders = TakeOrderModel::find($ids);

        if($take_orders->isEmpty()){
            return $this->error('提单不存在');
        }

        $status = $take_orders->pluck('status')->unique();
        if(count($status) > 1){
            return $this->error('提单状态不一致');
        }

        $orders = OrderModel::whereIn('take_order_id', $ids)
            ->get();

        if($orders->isEmpty()){
            return $this->error('提单下无入仓单');
        }

        $order_status = $orders->pluck('status')->unique();
        if(count($order_status) > 1){
            return $this->error('提单下入仓单状态不一致');
        }

        $entry_mode = $orders->first()->entry_mode;

        if(!in_array($entry_mode, OrderModel::HK_ENTER_MODE) && $order_status[0] != OrderModel::STATUS_PASS){
            return $this->error('提单下入仓单放行状态才能进行起飞操作');
        }

        DB::beginTransaction();
        try {
            TakeOrderModel::whereIn('id', $ids)
                ->update([
                    'status' => TakeOrderModel::STATUS_TAKEOFF,
//                    'show_sn' => TakeOrderModel::CUSTOMER_SHOW,
                    'take_off_time' => $time
                ]);

            OrderModel::whereIn('take_order_id', $ids)
                ->update([
                    'status' => OrderModel::STATUS_TAKEOFF,
                    'customer_status' => OrderModel::STATUS_TAKEOFF,
                    'take_off_time' => date('Y-m-d H:i:s')
                ]);

            DB::commit();

        } catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        //提单日志
        foreach ($ids as $id){
            $this->log($request, $id, '起飞');
            $this->node_log($request, $id, '起飞', $time);
        }

        return $this->success();
    }

    //抵达
    public function arrive(Request $request) {
        $ids = $request->input('ids', []);
        $time = $request->input('time', null);
//        if(!$time) {
//            return $this->error('请选择抵达时间');
//        }
        if(!is_array($ids) || empty($ids)) {
            return $this->error('请选择提单');
        }

        $take_orders = TakeOrderModel::find($ids);

        if($take_orders->isEmpty()){
            return $this->error('提单不存在');
        }

        $status = $take_orders->pluck('status')->unique();
        if(count($status) > 1){
            return $this->error('提单状态不一致');
        }
        if($status[0] != TakeOrderModel::STATUS_TAKEOFF){
            return $this->error('起飞状态的提单才能进行抵达操作');
        }


        DB::beginTransaction();
        try {
            TakeOrderModel::whereIn('id', $ids)
                ->update([
                    'status' => TakeOrderModel::STATUS_ARRIVE,
                    'arrive_time' => $time
                ]);

            OrderModel::whereIn('take_order_id', $ids)
                ->update([
                    'status' => OrderModel::STATUS_ARRIVE,
                    'customer_status' => OrderModel::STATUS_ARRIVE,
                ]);

            DB::commit();

        } catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        //提单日志
        foreach ($ids as $id){
            $this->log($request, $id, '抵达');
            $this->node_log($request, $id, '抵达', $time);
        }

        return $this->success();
    }

    //清关
    public function clearance(Request $request) {
        $ids = $request->input('ids', []);
        $time = $request->input('time', null);
//        if(!$time) {
//            return $this->error('请选择清关时间');
//        }
        if(!is_array($ids) || empty($ids)) {
            return $this->error('请选择提单');
        }

        $take_orders = TakeOrderModel::find($ids);

        if($take_orders->isEmpty()){
            return $this->error('提单不存在');
        }

        $status = $take_orders->pluck('status')->unique();
        if(count($status) > 1){
            return $this->error('提单状态不一致');
        }
        if($status[0] != TakeOrderModel::STATUS_ARRIVE){
            return $this->error('抵达状态的提单才能进行清关操作');
        }


        DB::beginTransaction();
        try {
            TakeOrderModel::whereIn('id', $ids)
                ->update([
                    'status' => TakeOrderModel::STATUS_CLEARANCE,
                    'clearance_time' => $time
                ]);

            OrderModel::whereIn('take_order_id', $ids)
                ->update([
                    'status' => OrderModel::STATUS_CLEARANCE,
                ]);

            DB::commit();

        } catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        //提单日志
        foreach ($ids as $id){
            $this->log($request, $id, '清关');
            $this->node_log($request, $id, '清关', $time);
        }

        return $this->success();
    }

    //签收
    public function sign(Request $request) {
        $ids = $request->input('ids', []);
        $time = $request->input('time', null);
//        if(!$time) {
//            return $this->error('请选择派送时间');
//        }
        if(!is_array($ids) || empty($ids)) {
            return $this->error('请选择提单');
        }

        $take_orders = TakeOrderModel::find($ids);

        if($take_orders->isEmpty()){
            return $this->error('提单不存在');
        }

        $status = $take_orders->pluck('status')->unique();
        if(count($status) > 1){
            return $this->error('提单状态不一致');
        }
        if($status[0] != TakeOrderModel::STATUS_ARRIVE && $status[0] != TakeOrderModel::STATUS_CLEARANCE){
            return $this->error('抵达或清关状态的提单才能进行派送操作');
        }

        DB::beginTransaction();
        try {
            TakeOrderModel::whereIn('id', $ids)
                ->update([
                    'status' => TakeOrderModel::STATUS_SIGN,
                    'delivery_time' => $time
                ]);

            OrderModel::whereIn('take_order_id', $ids)
                ->update([
                    'status' => OrderModel::STATUS_SIGNED,
                ]);

            DB::commit();

        } catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }


        //提单日志
        foreach ($ids as $id){
            $this->log($request, $id, '派送');
            $this->node_log($request, $id, '派送', $time);
        }

        return $this->success();
    }

    //展示提单号
    public function showsn(Request $request){
        $ids = $request->input('ids', []);
        if(!is_array($ids) || empty($ids)) {
            return $this->error('请选择提单');
        }

        TakeOrderModel::whereIn('id', $ids)
            ->update(['show_sn' => TakeOrderModel::CUSTOMER_SHOW]);

        //提单日志
        foreach ($ids as $id){
            $this->log($request, $id, '展示提单号');
        }

        return $this->success();
    }

    //不展示提单号
    public function hidesn(Request $request) {
        $ids = $request->input('ids', []);
        if(!is_array($ids) || empty($ids)) {
            return $this->error('请选择提单');
        }

        TakeOrderModel::whereIn('id', $ids)
            ->update(['show_sn' => TakeOrderModel::CUSTOMER_HIDE]);


        //提单日志
        foreach ($ids as $id){
            $this->log($request, $id, '不展示提单号');
        }
        return $this->success();
    }

    //录入结算重
    public function set_weight(Request $request, $id) {
        $params = $request->all();

        $validator = Validator::make($params, [
            'reality_weight' => 'required|numeric',
            'volume_weight' => 'required|numeric',
            'fee_weight' => 'required|numeric',
            'rec_p' => 'required|in:1,2,3,4,5,6'
        ], [
            'reality_weight.required' => '请输入结算重',
            'volume_weight.required' => '请输入体积中',
            'rec_p.required' => '请选择是否收泡',
            'fee_weight.required' => '缺少计费重',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }


        $take_order = TakeOrderModel::find($id);
        if(!$take_order) {
            return $this->error('提单不存在');
        }

        $auth = $request->get('auth');
        $take_order->reality_weight = $params['reality_weight'];
        $take_order->volume_weight = $params['volume_weight'];
        $take_order->fee_weight = $params['fee_weight'];
        $take_order->rec_p = $params['rec_p'];
        $take_order->settle_time = date('Y-m-d H:i:s');
        $take_order->set_weight_admin_id = $auth->id;
        $take_order->save();

        $rec = ReceivableGenericModel::where('take_order_id', $id)->first();

        if($rec){
            $rec->gross_weight = $params['reality_weight'];
            $rec->volume_weight = $params['volume_weight'];
            $rec->charging_weight = $params['fee_weight'];
            $rec->save();
        }

        $pay = PayableTakeOrderModel::where('take_order_id', $take_order->id)->first();
        if($pay){
            $pay->reality_weight = $params['reality_weight'];
            $pay->save();
        }


        //提单日志
        $this->log($request, $id, '录入结算重');


        return $this->success();
    }

    //完善资料
    public function perfect(Request $request, $id) {
        $params = $request->all();

        $take_order = TakeOrderModel::find($id);
        if(!$take_order) {
            return $this->error('提单不存在');
        }

        $auth = $request->get('auth');
        DB::transaction(function () use ($take_order, $params, $auth) {
            $dec_agent_id = $params['dec_agent_id'] ?? 0;
//            if($dec_agent_id && $take_order->fee_weight2) {
//                $agent = AgentModel::where('id', $dec_agent_id)->first();
//                if(!$agent) {
//                    throw new AppException('报关服务提供商错误');
//                }
//
//                if($agent->type != AgentModel::AGENT_TYPE_BG) {
//                    throw new AppException('报关服务提供商类型错误');
//                }
//
//                $cost = $agent->cost;
//                if(!$cost) {
//                    throw new AppException('报关服务提供商未设置计费');
//                }
//
//            }

            $take_order->operator = $params['operator'] ?? '';
            $take_order->servicer = $params['servicer'] ?? '';

            if($params['shipment_date']){
                $take_order->shipment_date = $params['shipment_date'] ?? '';
            }

            $take_order->cca = $params['cca'] ?? 0;
            $take_order->take_warehouse = $params['take_warehouse'] ?? '';
            $take_order->master = $params['master'] ?? '';
            $take_order->clr_agent_id = $params['clr_agent_id'] ?? 0;
            $take_order->dec_type = $params['dec_type'] ?? 0;
            $take_order->dec_method = $params['dec_method'] ?? 0;
            $take_order->dec_agent_id = $dec_agent_id;
            $take_order->fake_brand = $params['fake_brand'] ?? 0;
            $take_order->origin_ledger = $params['origin_ledger'] ?? 0;
            $take_order->mix_tick = $params['mix_tick'] ?? 0;
            $take_order->dec_incidentals = $params['dec_incidentals'] ?? 0;
            $take_order->dec_incidentals_remark = $params['dec_incidentals_remark'] ?? '';

            $take_order->slipt_order_count = $params['slipt_order_count'] ?? 0;

            $take_order->hk_land = $params['hk_land'] ?? 0;
            $take_order->hk_land_remark = $params['hk_land_remark'] ?? '';
            $take_order->hk_provide = $params['hk_provide'] ?? 0;
            $take_order->hk_provide_remark = $params['hk_provide_remark'] ?? '';
            $take_order->bj_3 = $params['bj_3'] ?? 0;
            $take_order->bj_3_remark = $params['bj_3_remark'] ?? '';
            $take_order->bj_8 = $params['bj_8'] ?? 0;
            $take_order->bj_8_remark = $params['bj_8_remark'] ?? '';
            $take_order->remark = $params['remark'] ?? '';

            $take_order->fill_admin_id = $auth->id;

            $take_order->save();

            //单证报关
            if(isset($params['separate_dec']) && is_array($params['separate_dec'])) {
                foreach ($params['separate_dec'] as $separate_dec) {
                    $order = OrderModel::where('take_order_id', $take_order->id)->find($separate_dec['id']);
                    if($order){
                        $order->separate_dec_weight = $separate_dec['separate_dec_weight'] ?? null;
                        $order->separate_dec_volume = $separate_dec['separate_dec_volume'] ?? null;
                        $order->separate_dec_page_fee = $separate_dec['separate_dec_page_fee'] ?? null;
                        $order->separate_dec_method = $separate_dec['separate_dec_method'] ?? null;
                        $order->separate_dec_other = $separate_dec['separate_dec_other'] ?? "";
                        $order->save();
                    }
                }
            }

            //香港装车杂费
            if(isset($params['hk_take']) && is_array($params['hk_take'])) {
                foreach ($params['hk_take'] as $hk_take) {
                    $order = OrderModel::where('take_order_id', $take_order->id)->find($hk_take['id']);
                    if($order){
                        $order->hk_take_weight = $hk_take['weight'] ?? 0;
                        $order->hk_take_fee = $hk_take['hk_take_fee'] ?? null;
                        $order->hk_take_sign_fee = $hk_take['hk_take_sign_fee'] ?? null;
                        $order->hk_take_park_fee = $hk_take['hk_take_park_fee'] ?? null;
                        $order->hk_take_remark = $hk_take['hk_take_remark'] ?? '';
                        $order->hk_take_tunnel_fee = $hk_take['hk_take_tunnel_fee'] ?? null;
                        $order->save();
                    }
                }
            }

            //香港自送杂费
            if(isset($params['hk_zs']) && is_array($params['hk_zs'])) {
                foreach ($params['hk_zs'] as $hk_zs) {
                    $order = OrderModel::where('take_order_id', $take_order->id)->find($hk_zs['id']);
                    if($order) {
                        $order->hk_zs_weight = $hk_zs['hk_zs_weight'] ?? null;
                        $order->hk_zs_sign_fee = $hk_zs['hk_zs_sign_fee'] ?? null;
                        $order->hk_zs_park_fee = $hk_zs['hk_zs_park_fee'] ?? null;
                        $order->hk_zs_remark = $hk_zs['hk_zs_remark'] ?? '';
                        $order->save();
                    }
                }
            }

            //万峰小件处理
            if(isset($params['wf']) && is_array($params['wf'])) {
                foreach ($params['wf'] as $wf) {
                    $order = OrderModel::where('take_order_id', $take_order->id)->find($wf['id']);
                    if(!$order) {
                        throw new AppException('万峰小件处理入仓单错误');
                    }

                    TakeOrderWfModel::where('order_id', $wf['id'])->delete();

                    $twf = new TakeOrderWfModel();
                    $twf->order_id = $wf['id'];
                    $twf->take_order_id = $take_order->id;
                    $twf->multi_pack_nums = $wf['multi_pack_nums'] ?? null;
                    $twf->multi_pack_weight = $wf['multi_pack_weight'] ?? null;
                    $twf->multi_pack_price = $wf['multi_pack_price'] ?? null;
                    $twf->carton_hm_nums = $wf['carton_hm_nums'] ?? null;
                    $twf->carton_hm_price = $wf['carton_hm_price'] ?? null;
                    $twf->put_express_nums = $wf['put_express_nums'] ?? null;
                    $twf->put_express_price = $wf['put_express_price'] ?? null;
                    $twf->dbc_nums = $wf['dbc_nums'] ?? null;
                    $twf->dbc_price = $wf['dbc_price'] ?? null;
                    $twf->yx_unload_weight = $wf['yx_unload_weight'] ?? null;
                    $twf->yx_unload_price = $wf['yx_unload_price'] ?? null;
                    $twf->sd_price = $wf['sd_price'] ?? null;
                    $twf->ztc_price = $wf['ztc_price'] ?? null;
                    $twf->ztc_after = $wf['ztc_after'] ?? null;
                    $twf->save();

                }
            }

            //特殊货物
            if(isset($params['special']) && is_array($params['special'])) {
                foreach ($params['special'] as $special) {

                    TakeOrderSpecialModel::where('take_order_id', $take_order->id)->delete();

                    $special_model = new TakeOrderSpecialModel();
                    $special_model->take_order_id = $take_order->id;
//                    $special_model->name = $special['name'] ?? null;
                    $special_model->weight = $special['weight'] ??  0;
                    $special_model->price = $special['price'] ??  0;
                    $special_model->type = $special['type'] ??  '';
                    $special_model->amount = $special['amount'] ??  0;
                    $special_model->save();
                }
            }

            $e = ReceivableGenericModel::where('take_order_id', $take_order->id)->first();
            if(!$e) {
                // 同步提单到应收
                $tp1 = new ReceivableGenericModel();
                $tp1->take_order_id = $take_order->id;
                $tp1->flight_id = $take_order->flight_id;
                $tp1->customer_id = $take_order->customer_id;
                $tp1->created_admin_id = $auth->id;
                $tp1->gross_weight = $take_order->reality_weight;
                $tp1->volume_weight = $take_order->volume_weight;
                $tp1->charging_weight = $take_order->fee_weight;
                $tp1->package_num = $take_order->orders?->sum('big_pkgs');
                $tp1->flight_date = $take_order->flight ? date('Y-m-d', strtotime($take_order->flight->take_off_time)) : '';
                $tp1->goods_attr = $take_order->goods_attr;
                $tp1->save();


                $customer = CustomerModel::find($take_order->customer_id);
                if($customer && $customer->is_big == 1){
                    $find_price = PriceModel::where('customer_id', $take_order->customer_id)
                        ->where('destination', $take_order->destination)
                        ->where('goods_attr', $take_order->goods_attr)
                        ->first();
                    if($find_price) {
                        $line_price = $find_price->line_price ?? 0;
                        $tp1->big_line_price = $line_price;
                        $tp1->total_amount = round($line_price * $take_order->reality_weight, 2);
                        $tp1->save();
                    }
                }else{
                    $find_prices = PriceDetailModel::where('customer_id', $take_order->customer_id)
                        ->where('route_id', $take_order->route_id)
                        ->where('goods_attr', $take_order->goods_attr)
                        ->get();

                    if(count($find_prices)) {
                        if(count($find_prices) > 1){
                            $take_order_air_company = $take_order->flight->air_company ?? '';
                            $find_price = null;
                            foreach ($find_prices as $val){
                                $air_company = $val->validity ?? '';
                                $air_company_arr = explode('/', $air_company);
                                if(in_array($take_order_air_company, $air_company_arr)){
                                    $find_price = $val;
                                    break;
                                }
                            }
                        }else{
                            $find_price = $find_prices[0];
                        }


                        if($find_price){
                            $price = 0;
                            if($take_order->fee_weight >= 1000){
                                $price = $find_price->price1000 ?? 0;
                            }elseif($take_order->fee_weight >= 500){
                                $price = $find_price->price500 ?? 0;
                            }elseif ($take_order->fee_weight >= 300){
                                $price = $find_price->price300 ?? 0;
                            }elseif ($take_order->fee_weight >= 100){
                                $price = $find_price->price100 ?? 0;
                            }elseif($take_order->fee_weight >= 45){
                                $price = $find_price->price45 ?? 0;
                            }
                            $tp1->air_freight_unit_price = $price;
                            $tp1->save();

                            $eml_price = \App\Models\client\PriceModel::find($find_price->price_id);

                            //空运费
                            if($price){
                                $rec_detail = new ReceivableGenericDetailModel();
                                $rec_detail->take_order_id = $take_order->id;
                                $rec_detail->customer_id = $take_order->customer_id;
                                $rec_detail->flight_id = $take_order->flight_id;
                                $rec_detail->generic_id = $tp1->id;
                                $rec_detail->name = '空运费';
                                $rec_detail->number = $take_order->reality_weight;
                                $rec_detail->price = $price;
                                $rec_detail->currency_id = $eml_price->currency_id ?? null;
                                $rec_detail->amount = round($price * $take_order->reality_weight, 2);
                                $rec_detail->save();
                            }

                            //提单费
                            $common_price = CommonPriceModel::first();
                            if($common_price){
                                $rec_detail = new ReceivableGenericDetailModel();
                                $rec_detail->take_order_id = $take_order->id;
                                $rec_detail->customer_id = $take_order->customer_id;
                                $rec_detail->flight_id = $take_order->flight_id;
                                $rec_detail->generic_id = $tp1->id;
                                $rec_detail->name = '提单费';
                                $rec_detail->number = 1;
                                $rec_detail->price = $common_price->tidan_price;
                                $rec_detail->currency_id = $eml_price->currency_id ?? null;
                                $rec_detail->amount = $common_price->tidan_price;
                                $rec_detail->save();
                            }
                        }
                    }
                }
            }else{
                $e->gross_weight = $take_order->reality_weight;
                $e->volume_weight = $take_order->volume_weight;
                $e->charging_weight = $take_order->fee_weight;
                $e->save();
            }

            //同步应收
//            $receive = ReceivableTakeOrderModel::where('take_order_id', $take_order->id)->first();
//            if(!$receive) {
//                $receive = new ReceivableTakeOrderModel();
//            }
//
//            $receive->take_order_id = $take_order->id;
//            $receive->customer_id = $take_order->customer_id;
//            $receive->flight_id = $take_order->flight_id;
//            $receive->destination = $take_order->destination;
//            $receive->goods_attr = $take_order->goods_attr;
//            $receive->master = $take_order->master;
//            $receive->big_pkgs = $take_order->orders?->sum('big_pkgs');
//            $receive->reality_weight = $take_order->reality_weight;
//            $receive->flight_date = $take_order->flight ? date('Y-m-d', strtotime($take_order->flight->take_off_time)) : '';
//            $receive->save();

            //同步应付
            $pay = PayableTakeOrderModel::where('take_order_id', $take_order->id)->first();
            if(!$pay) {
                $pay = new PayableTakeOrderModel();
            }
            $pay->take_order_id = $take_order->id;
            $pay->customer_id = $take_order->customer_id;
            $pay->flight_id = $take_order->flight_id;
            $pay->destination = $take_order->destination;
            $pay->goods_attr = $take_order->goods_attr;
            $pay->master = $take_order->master;
            $pay->big_pkgs = $take_order->orders?->sum('big_pkgs');
            $pay->reality_weight = $take_order->reality_weight;
            $pay->flight_date = $take_order->flight ? date('Y-m-d', strtotime($take_order->flight->take_off_time)) : '';
            $pay->operator = $take_order->operator;
            $pay->servicer = $take_order->servicer;
            $pay->save();


        });


        //提单日志
        $this->log($request, $id, '完善资料');

        return $this->success();
    }

    //详情
    public function detail(Request $request) {
        $id = $request->input('id');
        $take_order = TakeOrderModel::with(['orders', 'customer', 'flight'])->find($id);
        if(!$take_order) {
            return $this->error('提单不存在');
        }

        $storage_volume = $take_order->orders->sum('storage_volume');
        $des = CountryModel::whereIn('id', $take_order->flight->items->pluck('destination_id'))
                ->pluck('name')->toArray();

        $routes = RouteModel::whereIn('id', $take_order->flight->items->pluck('route_id'))
            ->pluck('name')->toArray();

        $flight_no = BaseFlightModel::whereIn('id', $take_order->flight->items->pluck('airline_flight_id'))
            ->pluck('flight_number')->toArray();

        //详情
        $detail = [
            'customer_name' => $take_order->customer->name ?? '',
            'customer_sn' => $take_order->customer->sn ?? '',
            'customer_type' => $take_order->customer->customer_type->name ?? '',
            'sn' => $take_order->sn,
            'status_name' => TakeOrderModel::STATUS_MAPS[$take_order->status] ?? '',
            'des_country' => implode(',', $des),
            'storage_volume' => $storage_volume,
            'storage_weight' => $take_order->orders->sum('storage_weight'),
            'route' => implode(',', $routes),
            'take_off_time' => $take_order->flight->take_off_time ?? '',
            'created_at' => $take_order->created_at->toDateTimeString(),
            'flight_no' => implode(',', $flight_no),
        ];

        //入仓单
        $orders = $take_order->orders->map(function($order) {
            $packages_name = DictionaryModel::whereIn('id', explode(',', $order->packages))
                ->pluck('name');
            return [
                'id' => $order->id,
                'sn' => $order->sn,
                'big_pkgs' => $order->big_pkgs,
                'pre_out_date' => $order->pre_out_date,
                'des_country_name' => $order->destination ??  '',
                'goods_attr_name' => OrderModel::GOODS_ATTR_MAPS[$order->goods_attr] ?? '',
                'clearance_mode_name' => OrderModel::CLEARANCE_MODE_MAPS[$order->clearance_mode] ?? '',
                'is_clearance' => $order->is_clearance,
                'pre_volume' => $order->pre_volume,
                'storage_weight' => $order->storage_weight,
                'packages_name' => $packages_name,
                'storage_time' => $order->storage_time,
            ];
        });

        $master = $take_order->master;
        if(empty($master)) {
            $master = $take_order->flight->carrier;
        }

        //完善资料
        $perfect = [
            'operator' => $take_order->operator,
            'servicer' => $take_order->servicer,
            'shipment_date' => $take_order->shipment_date,
            'cca' => $take_order->cca,
            'take_warehouse' => $take_order->take_warehouse,
            'master' => $master,
            'slipt_order_count' => $take_order->slipt_order_count,
            'clr_agent_id' => $take_order->clr_agent_id,
            'clr_agent_name' => $take_order->clr_agent->name ?? '',
            'dec_type' => $take_order->dec_type,
            'dec_type_name' => TakeOrderModel::DEC_TYPE_MAPS[$take_order->dec_type] ?? '',
            'dec_method' => $take_order->dec_method,
            'dec_method_name' => TakeOrderModel::DEC_METHOD_MAPS[$take_order->dec_method] ?? '',
            'dec_agent_id' => $take_order->dec_agent_id,
            'dec_agent_name' => $take_order->dec_agent->name ?? '',
            'fake_brand' => $take_order->fake_brand,
            'origin_ledger' => $take_order->origin_ledger,
            'mix_tick' => $take_order->mix_tick,
            'dec_incidentals' => $take_order->dec_incidentals,
            'dec_incidentals_remark' => $take_order->dec_incidentals_remark,
            'separate_dec_weight' => $take_order->separate_dec_weight,
            'separate_dec_volume' => $take_order->separate_dec_volume,
            'separate_dec_page_fee' => $take_order->separate_dec_page_fee,
            'hk_land' => $take_order->hk_land,
            'hk_land_remark' => $take_order->hk_land_remark,
            'hk_provide' => $take_order->hk_provide,
            'hk_provide_remark' => $take_order->hk_provide_remark,
            'bj_3' => $take_order->bj_3,
            'bj_3_remark' => $take_order->bj_3_remark,
            'bj_8' => $take_order->bj_8,
            'bj_8_remark' => $take_order->bj_8_remark,
            'remark' => $take_order->remark,
            'separate_dec' => $take_order->orders->map(function($order) {
                return [
                    'id' => $order->id,
                    'sn' => $order->sn,
                    'separate_dec_weight' => $order->separate_dec_weight,
                    'separate_dec_volume' => $order->separate_dec_volume,
                    'separate_dec_page_fee' => $order->separate_dec_page_fee,
                    'separate_dec_method' => $order->separate_dec_method,
                    'separate_dec_other' => $order->separate_dec_other,

                ];
            }),
            'hk_take' => $take_order->orders->map(function($order) {
                return [
                    'id' => $order->id,
                    'sn' => $order->sn,
                    'weight' => $order->hk_take_weight,
                    'hk_take_fee' => $order->hk_take_fee,
                    'hk_take_sign_fee' => $order->hk_take_sign_fee,
                    'hk_take_park_fee' => $order->hk_take_park_fee,
                    'hk_take_remark' => $order->hk_take_remark,
                ];
            }),
            'hk_zs' => $take_order->orders->map(function($order){
                return [
                    'id' => $order->id,
                    'sn' => $order->sn,
                    'hk_zs_weight' => $order->hk_zs_weight,
                    'hk_zs_sign_fee' => $order->hk_zs_sign_fee,
                    'hk_zs_park_fee' => $order->hk_zs_park_fee,
                    'hk_zs_remark' => $order->hk_zs_remark,
                ];
            }),
            'wf' => $take_order->wf->map(function($item) {
                return [
                    'id' => $item->id,
                    'order_id' => $item->order_id,
                    'sn' => $item->order->sn,
                    'multi_pack_nums' => $item->multi_pack_nums,
                    'multi_pack_weight' => $item->multi_pack_weight,
                    'multi_pack_price' => $item->multi_pack_price,
                    'carton_hm_nums' => $item->carton_hm_nums,
                    'carton_hm_price' => $item->carton_hm_price,
                    'put_express_nums' => $item->put_express_nums,
                    'put_express_price' => $item->put_express_price,
                    "dbc_nums" => $item->dbc_nums,
                    "dbc_price" => $item->dbc_price,
                    "yx_unload_weight" => $item->yx_unload_weight,
                    "yx_unload_price" => $item->yx_unload_price,
                    "sd_price" => $item->sd_price,
                    "ztc_price" => $item->ztc_price,
                    "ztc_after" => $item->ztc_after,
                ];
            }),
            'special' => $take_order->special->map(function($item) {
                return [
                    "id" => $item->id,
                    "take_order_id" => $item->take_order_id,
                    "weight" => $item->weight,
                    "price" => $item->price,
                    "type" => $item->type,
                    'amount' => $item->amount,
                ];
            })
        ];

        //操作日志
        $log_find = TakeOrderLogModel::with('create_admin')->where('take_order_id', $take_order->id)->get();
        $log = $log_find->map(function($item) {
            return [
                'name' => $item->name,
                'operator' => $item->create_admin->account ?? '',
                'created_at' => $item->created_at->format('Y-m-d H:i:s'),
            ];
        });

        //轨迹
        $node = [];
        $order_ids = $take_order->orders->pluck('id');
        $order_node_logs = OrderNodeLogModel::with(['order', 'create_admin'] )->whereIn('order_id', $order_ids)->get();
        foreach ($order_node_logs as $item){
            $sn = $item->order->sn ?? '';
            $node[] = [
                'name' => $item->name . '(' . $sn . ')',
                'operator' => $item->create_admin->account ?? '',
                'time' => $item->time,
                'created_at' => $item->created_at->format('Y-m-d H:i:s'),
            ];
        }

        $take_order_node_logs = TakeOrderNodeLogModel::with('create_admin')->where('take_order_id', $take_order->id)->get();
        foreach ($take_order_node_logs as $item){
            $node[] = [
                'name' => $item->name,
                'operator' => $item->create_admin->account ?? '',
                'time' => $item->time,
                'created_at' => $item->created_at->format('Y-m-d H:i:s'),
            ];
        }



        return $this->success([
            'detail' => $detail,
            'orders' => $orders,
            'perfect' => $perfect,
            'log' => $log,
            'node' => $node,
        ]);

    }

    /**
     * 导出Excel
     * 请求示例:
     * {
     *   "sns": "T202412070001,T202412070002", // 提单号,多个用逗号分隔
     *   "customer_type": "1", // 客户类型ID
     *   "customer_name": "客户名称", // 客户名称
     *   "flight_number": "CZ3001", // 航班号
     *   "status": "1", // 提单状态
     *   "des_country_id": "1", // 目的地国家ID
     *   "customer_visible": "1", // 客户可见(1:显示,2:隐藏)
     *   "settle_again": "1", // 是否再结算(0:未结算,1:已结算)
     *   "startTime": "2024-12-01 00:00:00", // 起飞开始时间
     *   "endTime": "2024-12-31 23:59:59", // 起飞结束时间
     *   "fill_admin_id": "1" // 填写人员ID
     * }
     */
    public function export(Request $request){
        $query = $this->buildQuery($request);
        $items = $query->orderBy('id', 'desc')->get();
        $list = $this->formatListData($items);

        // 转换为导出格式，只保留基础字段，不包含嵌套的orders和wf
        $exportData = $list->map(function($item) {
            return [
                $item['customer_name'],
                $item['sn'],
                $item['status_name'],
                $item['route'],
                $item['take_off_time'],
                $item['flight_no'],
                $item['order_count'],
                $item['big_pkgs'],
                $item['arrive_port_code'],
                $item['storage_volume'],
                $item['volume_weight'],
                $item['storage_weight'],
                $item['reality_weight'],
                $item['rec_p'],
                $item['fee_weight'],
            ];
        });

        return Excel::download(new TakeOrderExport($exportData), '提单数据.xlsx');
    }

    /**
     * 客户端航班信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function customer_flight_info(Request $request)
    {
        $id = $request->input('id',  '');
        $flight_info = $request->input('flight_info',  '');
        $flight_info_show = $request->input('flight_info_show',  1);

        $take_order = TakeOrderModel::find($id);

        $take_order->flight_info = $flight_info;
        $take_order->flight_info_show = $flight_info_show;
        $take_order->save();


        //提单日志
        $this->log($request, $id, '客户端航班信息');

        return $this->success();

    }

    /**
     * 草单文件上传
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function grass_file(Request $request)
    {
        $id = $request->input('id',  '');
        $grass_file = $request->input('file',  '');

        if(!$grass_file){
            return $this->error('请选择文件');
        }

        $take_order = TakeOrderModel::find($id);
        $grass_files = $take_order->grass_files;

        if($grass_files){
            $grass_files = json_decode($grass_files, true);
        }else{
            $grass_files = [];
        }
        $grass_files[] = $grass_file;
        $grass_files = array_values($grass_files);
        $take_order->grass_files = json_encode($grass_files);
        $take_order->save();

        //提单日志
        $this->log($request, $id, '草单文件上传');

        return $this->success(['new_files' => $grass_files], '上传成功');
    }

    /**
     * 草单文件删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function grass_file_delete(Request $request)
    {
        $id = $request->input('id',  '');
        $grass_file = $request->input('file_path',  '');
        $take_order = TakeOrderModel::find($id);
        $grass_files = $take_order->grass_files;
        if($grass_files){
            $grass_files = json_decode($grass_files, true);
        }else{
            $grass_files = [];
        }
        if(($key = array_search($grass_file, $grass_files)) !== false) {
            unset($grass_files[$key]);
        }
        $grass_files = array_values($grass_files);
        $take_order->grass_files = json_encode($grass_files);
        $take_order->save();

        //提单日志
        $this->log($request, $id, '草单文件删除');

        return $this->success(['new_files' => $grass_files], '删除成功');
    }

    /**
     * 最终提单文件上传
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function final_file(Request $request)
    {
        $id = $request->input('id',  '');
        $final_file = $request->input('file',  '');

        if(!$final_file){
            return $this->error('请选择文件');
        }

        $take_order = TakeOrderModel::find($id);
        $final_files = $take_order->final_files;
        if($final_files){
            $final_files = json_decode($final_files, true);
        }else{
            $final_files = [];
        }
        $final_files[] = $final_file;
        $final_files = array_values($final_files);
        $take_order->final_files = json_encode($final_files);
        $take_order->save();

        //提单日志
        $this->log($request, $id, '客户提单文件上传');

        return $this->success(['new_file' => $final_files], '上传成功');
    }

    /**
     * 提单文件删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function final_file_delete(Request $request)
    {
        $id = $request->input('id',  '');
        $final_file = $request->input('file_path',  '');
        $take_order = TakeOrderModel::find($id);
        $final_files = $take_order->final_files;
        if($final_files){
            $final_files = json_decode($final_files, true);
        }else{
            $final_files = [];
        }
        if(($key = array_search($final_file, $final_files)) !== false) {
            unset($final_files[$key]);
        }
        $final_files = array_values($final_files);
        $take_order->final_files = json_encode($final_files);
        $take_order->save();

        //提单日志
        $this->log($request, $id, '客户提单文件删除');

        return $this->success(['new_file' => $final_files], '删除成功');
    }


    /**
     * 航司文件上传
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function aircompany_file(Request $request)
    {
        $id = $request->input('id',  '');
        $aircompany_file = $request->input('file',  '');

        if(!$aircompany_file){
            return $this->error('请选择文件');
        }

        $take_order = TakeOrderModel::find($id);
        $aircompany_files = $take_order->aircompany_files;

        if($aircompany_files){
            $aircompany_files = json_decode($aircompany_files, true);
        }else{
            $aircompany_files = [];
        }
        $aircompany_files[] = $aircompany_file;
        $aircompany_files = array_values($aircompany_files);
        $take_order->aircompany_files = json_encode($aircompany_files);
        $take_order->save();

        //提单日志
        $this->log($request, $id, '航司文件上传');

        return $this->success(['new_files' => $aircompany_files], '上传成功');
    }

    /**
     * 航司文件删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function aircompany_file_delete(Request $request)
    {
        $id = $request->input('id',  '');
        $aircompany_file = $request->input('file_path',  '');
        $take_order = TakeOrderModel::find($id);
        $aircompany_files = $take_order->aircompany_files;
        if($aircompany_files){
            $aircompany_files = json_decode($aircompany_files, true);
        }else{
            $aircompany_files = [];
        }
        if(($key = array_search($aircompany_file, $aircompany_files)) !== false) {
            unset($aircompany_files[$key]);
        }
        $aircompany_files = array_values($aircompany_files);
        $take_order->aircompany_files = json_encode($aircompany_files);
        $take_order->save();

        //提单日志
        $this->log($request, $id, '航司文件删除');

        return $this->success(['new_files' => $aircompany_files], '删除成功');
    }


    /**
     * 操作日志
     * @param $request
     * @param $take_order_id
     * @param $name
     * @return void
     */
    public function log($request, $take_order_id, $name)
    {
        $auth = $request->get('auth');

        $log = new TakeOrderLogModel();
        $log->take_order_id = $take_order_id;
        $log->name = $name;
        $log->url = $request->url();
        $log->created_admin_id = $auth->id;
        $log->save();

    }

    /**
     * 节点日志
     * @param $request
     * @param $order_id
     * @param $name
     * @param $time
     * @return void
     */
    public function node_log($request, $take_order_id, $name, $time)
    {
        $auth = $request->get('auth');

        $log = new TakeOrderNodeLogModel();
        $log->take_order_id = $take_order_id;
        $log->name = $name;
        $log->time = $time;
        $log->url = $request->url();
        $log->created_admin_id = $auth->id;
        $log->save();

    }

}

